package com.rayboo.service;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rayboo.model.AdminUser;

/**
 * 
 * AdminUserService
 * 
 * @author ray
 * @date 2016年9月8日 下午8:10:19
 *
 */
@Service
public class AdminUserService {

	private static Gson gson = new Gson();

	/**
	 * 读取users.json中的用户信息
	 * 
	 * @return
	 */
	private List<Map<String, Object>> getUsers() {
		List<Map<String, Object>> users = new ArrayList<>();
		Resource resource = new ClassPathResource("data/users.json");
		try (InputStream in = resource.getInputStream(); Reader reader = new InputStreamReader(in)) {
			users = gson.fromJson(reader, new TypeToken<List<Map<String, Object>>>() {
			}.getType());
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return users;
	}

	public String encodePassword(String username, String password) {
		return new Md5PasswordEncoder().encodePassword(password, username);
	}

	/**
	 * 根据用户名获取用户信息
	 * 
	 * @param username
	 * @return
	 */
	public AdminUser findByUsername(String username) {
		List<Map<String, Object>> users = getUsers();
		AdminUser user = new AdminUser();
		for (Map<String, Object> map : users) {
			if (username.equals(map.get("username"))) {
				user.setId(Long.valueOf(map.get("id").toString()));
				String uname = map.get("username").toString();
				user.setUsername(uname);
				String pwd = encodePassword(uname, map.get("password").toString());
				user.setPassword(pwd);
				break;
			}
		}
		return user;
	}

}
